package jmp.client.view;

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.sound.sampled.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.filechooser.*;

import jmp.client.event.*;
import jmp.client.util.*;
import jmp.client.player.*;

public class PanelPlayer extends JPanel {

    private boolean isRun;
    private JFileChooser jfc;
    private MusicPlayer player;
    private javax.swing.Timer relogio;
    private int musicaAtual, barraProgresso, minutos, segundos;
    private long totalMusica;
    private File diretorioAtual;

    public PanelPlayer() {
        initComponents();

        tabelaMusicas.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {

                super.getTableCellRendererComponent(table, value, isSelected,
                        hasFocus, row, column);

                for (int i = 0; i < tabelaMusicas.getRowCount(); i++) {
                    if (row % 2 == 0) {
                        setBackground(new Color(198, 232, 0xFF));
                    } else {
                        setBackground(null);
                    }
                }

                if (isSelected) {
                    setBackground(Color.BLACK);
                    setForeground(Color.WHITE);
                    setFont(new Font(getFont().getName(), Font.BOLD, getFont().getSize()));
                } else {
                    setForeground(Color.BLACK);
                    setFont(new Font(getFont().getName(), Font.PLAIN, getFont().getSize()));
                }

                setBorder(null);

                return this;
            }
        });

        this.isRun = false;
        player = new MusicPlayer();

        tabelaMusicas.setShowGrid(false);
        tabelaMusicas.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        lblPlayPause.setToolTipText("Play / Pause");
        lblStop.setToolTipText("Stop");
        lblAnterior.setToolTipText("Anterior");
        lblProximo.setToolTipText("Proximo");
        lblAbrir.setToolTipText("Abrir música / playlist");
        lblSalvarPlaylist.setToolTipText("Salvar playlist");
        lblOrdemAleatoria.setToolTipText("Ordem aleatória");
        lblRepetir.setToolTipText("Repetir");
        lblVoltar.setToolTipText("Voltar");
        lblAvancar.setToolTipText("Avançar");
        lblAcima.setToolTipText("Acima");
        lblProcurar.setToolTipText("Localizar diretorio");

        for (Component c : panelControles.getComponents()) {
            if (c instanceof JLabel) {
                c.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            }
        }

        for (Component c : panelArquivos.getComponents()) {
            if (c instanceof JLabel) {
                c.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            }
        }

        player.addMusicPlayerListener(new MusicPlayerListener() {

            public void musicaAlterada(MusicPlayerEvent evt) {
            //tabelaMusicas.getModel().setValueAt(">", musicaAtual, 0);
            }

            public void musicaAdicionada(MusicPlayerEvent evt) {

            }

            public void musicaRemovida(MusicPlayerEvent evt) {

            }

            public void musicaAtualComecou(MusicPlayerEvent evt) {
                try {
                    totalMusica = Long.parseLong(evt.getMusicaAtual().getInformacaoAudio("duration").toString()) / 100;
                    minutos = 0;
                    segundos = 0;
                    relogio.start();
                    
                    
                    // barraMusica.setMaximum(((int) totalMusica / 1000));
                    // barraMusica.setValue(0);
                } catch (UnsupportedAudioFileException ex) {
                    ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            public void musicaAtualTerminou(MusicPlayerEvent evt) {
                relogio.stop();
            }
        });

        tabelaMusicas.getColumnModel().getColumn(0).setPreferredWidth(2);
        tabelaMusicas.getColumnModel().getColumn(1).setPreferredWidth(153);
        tabelaMusicas.getColumnModel().getColumn(2).setPreferredWidth(130);
        tabelaMusicas.getColumnModel().getColumn(3).setPreferredWidth(130);
        tabelaMusicas.getColumnModel().getColumn(4).setPreferredWidth(30);

        lista.setCellRenderer(new ListaRenderer());
        lista.setModel(new DefaultListModel());
        this.diretorioAtual = new File("/");
        this.listarArquivos();
        
        relogio = new javax.swing.Timer(1000, new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                segundos++;
                
                if(segundos > 59){
                    segundos = 0;
                    minutos++;
                }
                
                lblRelogio.setText(String.format("%02d:%02d", minutos, segundos));
            }

        });
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        scroll = new javax.swing.JScrollPane();
        tabelaMusicas = new javax.swing.JTable();
        panelControles = new javax.swing.JPanel();
        barraMusica = new javax.swing.JSlider();
        lblPlayPause = new javax.swing.JLabel();
        lblStop = new javax.swing.JLabel();
        lblAnterior = new javax.swing.JLabel();
        lblProximo = new javax.swing.JLabel();
        lblAbrir = new javax.swing.JLabel();
        lblSalvarPlaylist = new javax.swing.JLabel();
        lblRepetir = new javax.swing.JLabel();
        lblOrdemAleatoria = new javax.swing.JLabel();
        lblRelogio = new javax.swing.JLabel();
        panelArquivos = new javax.swing.JPanel();
        cmbHistorico = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        lista = new javax.swing.JList();
        lblProcurar = new javax.swing.JLabel();
        lblAvancar = new javax.swing.JLabel();
        lblAcima = new javax.swing.JLabel();
        lblVoltar = new javax.swing.JLabel();

        tabelaMusicas.setModel(new ModeloTabela());
        tabelaMusicas.setDragEnabled(true);
        tabelaMusicas.setGridColor(new java.awt.Color(255, 255, 255));
        tabelaMusicas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaMusicasMouseClicked(evt);
            }
        });
        tabelaMusicas.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tabelaMusicasKeyPressed(evt);
            }
        });
        scroll.setViewportView(tabelaMusicas);

        panelControles.setBackground(new java.awt.Color(198, 232, 255));
        panelControles.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        barraMusica.setBackground(new java.awt.Color(255, 255, 255));
        barraMusica.setValue(0);
        barraMusica.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        barraMusica.setEnabled(false);

        lblPlayPause.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/play.jpg"))); // NOI18N
        lblPlayPause.setOpaque(true);
        lblPlayPause.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblPlayPauseMouseReleased(evt);
            }
        });

        lblStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/stop.jpg"))); // NOI18N
        lblStop.setOpaque(true);
        lblStop.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblStopMouseReleased(evt);
            }
        });

        lblAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/anterior.jpg"))); // NOI18N
        lblAnterior.setOpaque(true);
        lblAnterior.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblAnteriorMouseReleased(evt);
            }
        });

        lblProximo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/proximo.jpg"))); // NOI18N
        lblProximo.setOpaque(true);
        lblProximo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblProximoMouseReleased(evt);
            }
        });

        lblAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/abrir.jpg"))); // NOI18N
        lblAbrir.setOpaque(true);
        lblAbrir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblAbrirMouseReleased(evt);
            }
        });

        lblSalvarPlaylist.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/salvar.jpg"))); // NOI18N
        lblSalvarPlaylist.setOpaque(true);
        lblSalvarPlaylist.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblSalvarPlaylistMouseReleased(evt);
            }
        });

        lblRepetir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/repetirDesativado.jpg"))); // NOI18N
        lblRepetir.setOpaque(true);
        lblRepetir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblRepetirMouseReleased(evt);
            }
        });

        lblOrdemAleatoria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/ordemAleatoriaDesativado.jpg"))); // NOI18N
        lblOrdemAleatoria.setOpaque(true);
        lblOrdemAleatoria.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblOrdemAleatoriaMouseReleased(evt);
            }
        });

        lblRelogio.setBackground(new java.awt.Color(255, 255, 255));
        lblRelogio.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblRelogio.setText("00:00");
        lblRelogio.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lblRelogio.setOpaque(true);

        javax.swing.GroupLayout panelControlesLayout = new javax.swing.GroupLayout(panelControles);
        panelControles.setLayout(panelControlesLayout);
        panelControlesLayout.setHorizontalGroup(
            panelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelControlesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelControlesLayout.createSequentialGroup()
                        .addComponent(barraMusica, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblRelogio, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelControlesLayout.createSequentialGroup()
                        .addComponent(lblPlayPause)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblStop)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblAnterior)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblProximo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 94, Short.MAX_VALUE)
                        .addComponent(lblRepetir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblOrdemAleatoria)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblSalvarPlaylist)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblAbrir)))
                .addContainerGap())
        );
        panelControlesLayout.setVerticalGroup(
            panelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelControlesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblPlayPause)
                    .addComponent(lblAbrir)
                    .addGroup(panelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblStop)
                        .addComponent(lblAnterior)
                        .addComponent(lblProximo))
                    .addComponent(lblSalvarPlaylist)
                    .addComponent(lblOrdemAleatoria)
                    .addComponent(lblRepetir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelControlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblRelogio, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                    .addComponent(barraMusica, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
                .addContainerGap())
        );

        panelArquivos.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lista.setLayoutOrientation(javax.swing.JList.VERTICAL_WRAP);
        lista.setVisibleRowCount(10);
        lista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lista);

        lblProcurar.setBackground(new java.awt.Color(204, 204, 204));
        lblProcurar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/procurar.jpg"))); // NOI18N
        lblProcurar.setOpaque(true);
        lblProcurar.setPreferredSize(new java.awt.Dimension(25, 25));
        lblProcurar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblProcurarMouseReleased(evt);
            }
        });

        lblAvancar.setBackground(new java.awt.Color(204, 204, 204));
        lblAvancar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/avancar.jpg"))); // NOI18N
        lblAvancar.setOpaque(true);

        lblAcima.setBackground(new java.awt.Color(204, 204, 204));
        lblAcima.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/acima.jpg"))); // NOI18N
        lblAcima.setOpaque(true);
        lblAcima.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lblAcimaMouseReleased(evt);
            }
        });

        lblVoltar.setBackground(new java.awt.Color(204, 204, 204));
        lblVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jmp/client/player/imagens/voltar.jpg"))); // NOI18N
        lblVoltar.setOpaque(true);

        javax.swing.GroupLayout panelArquivosLayout = new javax.swing.GroupLayout(panelArquivos);
        panelArquivos.setLayout(panelArquivosLayout);
        panelArquivosLayout.setHorizontalGroup(
            panelArquivosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelArquivosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelArquivosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
                    .addGroup(panelArquivosLayout.createSequentialGroup()
                        .addComponent(cmbHistorico, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblAvancar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblAcima, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblProcurar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        panelArquivosLayout.setVerticalGroup(
            panelArquivosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelArquivosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelArquivosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cmbHistorico)
                    .addComponent(lblProcurar, 0, 0, Short.MAX_VALUE)
                    .addComponent(lblAvancar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblVoltar, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                    .addComponent(lblAcima, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE)
                    .addComponent(panelControles, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelArquivos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelArquivos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(panelControles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    private void lblPlayPauseMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblPlayPauseMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            if (tabelaMusicas.getRowCount() == 0) {
                return;
            }

            if (player.getEstadoMusica().equals(Estado.PLAY)) {
                this.pause();
            } else if (player.getEstadoMusica().equals(Estado.PAUSE)) {
                this.continuar();
            } else {
                this.play();
            }
        }
    }//GEN-LAST:event_lblPlayPauseMouseReleased

    private void tabelaMusicasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaMusicasMouseClicked
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
            this.play(tabelaMusicas.getSelectedRow());
        }
    }//GEN-LAST:event_tabelaMusicasMouseClicked

    private void lblAbrirMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblAbrirMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            jfc = new JFileChooser();
            jfc.setSelectedFile(null);
            jfc.setMultiSelectionEnabled(true);
            jfc.setApproveButtonText("Abrir");
            jfc.setDialogTitle("Abrir arquivos");
            jfc.setFileFilter(new FileNameExtensionFilter("Playlists (.jmp)", "jmp"));
            jfc.setFileFilter(new FileNameExtensionFilter("Arquivos mp3 (.mp3)", "mp3"));
            jfc.showOpenDialog(this);

            boolean estaVazio = false;

            try {
                for (File f : jfc.getSelectedFiles()) {
                    if (f.getName().substring(f.getName().length() - 3).equals("jmp")) {
                        if(this.isRun){
                            this.stop();
                        }
                        player.abrirPlaylist(f);
                        java.util.List<String[]> l = new ArrayList<String[]>();

                        for (Musica m : player.getPlaylist()) {
                            l.add(this.getInformacoesMusica(m));
                        }

                        this.apagarTabela();
                        this.preencherTabela(l);
                        this.play(0);
                        return;
                    }

                    if (tabelaMusicas.getRowCount() == 0) {
                        estaVazio = true;
                    }

                    Musica m = new Musica(f);
                    player.addMusica(m);

                    ((ModeloTabela) tabelaMusicas.getModel()).addRow(this.getInformacoesMusica(m));
                }

                if (estaVazio) {
                    this.play(0);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (LineUnavailableException ex) {
                ex.printStackTrace();
            } catch (UnsupportedAudioFileException ex) {
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_lblAbrirMouseReleased

    private void lblSalvarPlaylistMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblSalvarPlaylistMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            if (tabelaMusicas.getRowCount() == 0) {
                JOptionPane.showMessageDialog(this, "Adicione ao menos 1 musica antes de salvar a playlist!",
                        "Erro!", JOptionPane.ERROR_MESSAGE);
                return;
            }

            jfc = new JFileChooser();
            jfc.setSelectedFile(null);
            jfc.setApproveButtonText("Salvar");
            jfc.setDialogTitle("Salvar playlist");
            jfc.setFileFilter(new FileNameExtensionFilter("Playlist (.jmp)", "jmp"));
            jfc.showSaveDialog(this);

            try {
                File f = jfc.getSelectedFile();
                f.renameTo(new File(jfc.getName() + ".jmp"));
                player.salvarPlaylist(f);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_lblSalvarPlaylistMouseReleased

    private void tabelaMusicasKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tabelaMusicasKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
            if (tabelaMusicas.getSelectedRow() == this.musicaAtual) {
                this.stop();
            }
            player.removeMusica(tabelaMusicas.getSelectedRow());
            ((ModeloTabela) tabelaMusicas.getModel()).removeRow(tabelaMusicas.getSelectedRow());
        }
    }//GEN-LAST:event_tabelaMusicasKeyPressed

    private void lblRepetirMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblRepetirMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            if (player.isRepetir()) {
                player.setRepetir(false);
                lblRepetir.setIcon(this.getImagem("repetirDesativado"));
            } else {
                player.setRepetir(true);
                lblRepetir.setIcon(this.getImagem("repetirAtivado"));
                lblOrdemAleatoria.setIcon(this.getImagem("ordemAleatoriaDesativado"));
            }
        }
    }//GEN-LAST:event_lblRepetirMouseReleased

    private void lblOrdemAleatoriaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblOrdemAleatoriaMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            if (player.isOrdemAleatoria()) {
                player.setOrdemAleatoria(false);
                lblOrdemAleatoria.setIcon(this.getImagem("ordemAleatoriaDesativado"));
            } else {
                player.setOrdemAleatoria(true);
                lblOrdemAleatoria.setIcon(this.getImagem("ordemAleatoriaAtivado"));
                lblRepetir.setIcon(this.getImagem("repetirDesativado"));
            }
        }
    }//GEN-LAST:event_lblOrdemAleatoriaMouseReleased

    private void lblAnteriorMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblAnteriorMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            try {
                player.anterior();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (LineUnavailableException ex) {
                ex.printStackTrace();
            } catch (UnsupportedAudioFileException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_lblAnteriorMouseReleased

    private void lblProximoMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblProximoMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            try {
                player.proxima();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (LineUnavailableException ex) {
                ex.printStackTrace();
            } catch (UnsupportedAudioFileException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_lblProximoMouseReleased

    private void lblStopMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblStopMouseReleased
        this.stop();
    }//GEN-LAST:event_lblStopMouseReleased

    private void lblProcurarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblProcurarMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            jfc = new JFileChooser();
            jfc.setSelectedFile(null);
            jfc.setApproveButtonText("Abrir");
            jfc.setDialogTitle("Abrir diretório");
            jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jfc.showOpenDialog(this);

            this.diretorioAtual = jfc.getSelectedFile();
            this.listarComboBox();
            this.listarArquivos();
        }
    }//GEN-LAST:event_lblProcurarMouseReleased

    private void listaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaMouseClicked
        if (evt.getClickCount() == 2) {
            if (((File) lista.getSelectedValue()).isDirectory()) {
                this.diretorioAtual = (File) lista.getSelectedValue();
                this.listarComboBox();
                this.listarArquivos();
            } else {
                return;
            }
        }
    }//GEN-LAST:event_listaMouseClicked

    private void lblAcimaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblAcimaMouseReleased
        if (evt.getButton() == MouseEvent.BUTTON1) {
            this.diretorioAtual = diretorioAtual.getParentFile();
            this.listarComboBox();
            this.listarArquivos();
        }
    }//GEN-LAST:event_lblAcimaMouseReleased

    private String[] getInformacoesMusica(Musica m) throws UnsupportedAudioFileException, 
            UnsupportedAudioFileException, UnsupportedAudioFileException, IOException {
        String[] info = new String[5];

        String nome = null;
        String autor = null;
        String album = null;
        String duracao = null;

        if (m.getInformacaoAudio("title") == null ||
                m.getInformacaoAudio("title").toString().equals("")) {
            nome = m.getArquivo().getName();
        } else {
            nome = m.getInformacaoAudio("title").toString();
        }

        if (!(m.getInformacaoAudio("author") == null)) {
            autor = m.getInformacaoAudio("author").toString();
        }

        if (!(m.getInformacaoAudio("album") == null)) {
            album = m.getInformacaoAudio("album").toString();
        }

        String d = m.getInformacaoAudio("duration").toString();
        long seg = Long.parseLong(d);
        seg /= 1000000;
        long min = seg / 60;
        seg %= 60;
        duracao = String.format("%02d:%02d", min, seg);

        info[0] = null;
        info[1] = nome;
        info[2] = autor;
        info[3] = album;
        info[4] = duracao;

        return info;
    }
    
    private void preencherTabela(java.util.List<String[]> playlist) {
        for (String[] musica : playlist) {
            ((ModeloTabela) tabelaMusicas.getModel()).addRow(musica);
        }
    }

    private void apagarTabela() {
        for (int i = 0; i < tabelaMusicas.getRowCount(); i++) {
            ((ModeloTabela) tabelaMusicas.getModel()).removeRow(i);
        }
    }

    private void continuar() {
        try {
            player.continuar();
            lblPlayPause.setIcon(this.getImagem("pause"));
//            relogio.continuar();
//            this.iniciarBarraStatus();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (LineUnavailableException ex) {
            ex.printStackTrace();
        }
    }

    private void play() {
        try {
            player.play();
//            relogio.iniciar();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (LineUnavailableException ex) {
            ex.printStackTrace();
        }
    }

    private void play(int index) {
        try {
            if (index < 0 && tabelaMusicas.getRowCount() > 0) {
                index = 0;
            }
            this.isRun = true;
            this.musicaAtual = index;
//            relogio.iniciar();
//            this.iniciarBarraStatus();
            player.play(index);
            lblPlayPause.setIcon(this.getImagem("pause"));
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (LineUnavailableException ex) {
            ex.printStackTrace();
        } catch (UnsupportedAudioFileException ex) {
            ex.printStackTrace();
        }
    }

    private void stop() {
        try {
            this.isRun = false;
            this.barraProgresso = 0;
            player.stop();
//            relogio.zerar();
            lblPlayPause.setIcon(this.getImagem("play"));
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (LineUnavailableException ex) {
            ex.printStackTrace();
        } catch (UnsupportedAudioFileException ex) {
            ex.printStackTrace();
        }
    }

    private void pause() {
        this.isRun = false;
        player.pause();
//        relogio.parar();
        lblPlayPause.setIcon(this.getImagem("play"));
    }

/*    private void iniciarBarraStatus() {
        new Thread(new Runnable() {

            public void run() {
                try {
                    while (player.getEstadoMusica().equals(Estado.PLAY)) {
                        Thread.sleep(100);
                        barraMusica.setValue(barraProgresso++);
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();


    }*/

    private void listarArquivos() {
        String extensao = null;
        File[] arquivos = diretorioAtual.listFiles();

        ((DefaultListModel) lista.getModel()).clear();

        for (File f : arquivos) {
            if (f.isDirectory()) {
                ((DefaultListModel) lista.getModel()).addElement(f);
            }
        }

        for (File f : arquivos) {
            if (!f.isDirectory()) {
                extensao = f.getName();
                extensao = extensao.substring(extensao.length() - 3);

                if (extensao.equals("mp3")) {
                    ((DefaultListModel) lista.getModel()).addElement(f);
                }

            }
        }
    }

    private ImageIcon getImagem(String imagem) {
        return new ImageIcon(getClass().getResource("/jmp/client/player/imagens/" + imagem + ".jpg"));
    }

    private void listarComboBox() {
        String s = diretorioAtual.getName();

        boolean existe = false;

        for (int i = 0; i < cmbHistorico.getItemCount(); i++) {
            if (s.equals(cmbHistorico.getItemAt(i))) {
                existe = true;
            }
        }

        if (!existe) {
            cmbHistorico.addItem(s);
        }

        cmbHistorico.getModel().setSelectedItem(s);
    }

    private class ListaRenderer extends JLabel implements ListCellRenderer {

        public ListaRenderer() {
            setOpaque(true);
        }

        public Component getListCellRendererComponent(JList list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {

            if (!(value instanceof File)) {
                throw new IllegalArgumentException("O argumento deve ser uma instancia de File");
            }

            String s = ((File) value).getName();
            s = s.length() > 25 ? s.substring(0, 25) + "..." : s;
            setText(s);

            if (((File) value).isDirectory()) {
                setIcon(getImagem("pasta"));
            } else {
                setIcon(getImagem("musica"));
            }

            if (isSelected) {
                setForeground(list.getSelectionForeground());
                setBackground(list.getSelectionBackground());
            } else {
                setForeground(list.getForeground());
                setBackground(list.getBackground());
            }

            setToolTipText(((File) value).getName());

            return this;
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSlider barraMusica;
    private javax.swing.JComboBox cmbHistorico;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAbrir;
    private javax.swing.JLabel lblAcima;
    private javax.swing.JLabel lblAnterior;
    private javax.swing.JLabel lblAvancar;
    private javax.swing.JLabel lblOrdemAleatoria;
    private javax.swing.JLabel lblPlayPause;
    private javax.swing.JLabel lblProcurar;
    private javax.swing.JLabel lblProximo;
    private javax.swing.JLabel lblRelogio;
    private javax.swing.JLabel lblRepetir;
    private javax.swing.JLabel lblSalvarPlaylist;
    private javax.swing.JLabel lblStop;
    private javax.swing.JLabel lblVoltar;
    private javax.swing.JList lista;
    private javax.swing.JPanel panelArquivos;
    private javax.swing.JPanel panelControles;
    private javax.swing.JScrollPane scroll;
    private javax.swing.JTable tabelaMusicas;
    // End of variables declaration//GEN-END:variables
    
    public static void main(String[] args) {
        JFrame j = new JFrame();
        j.getContentPane().add(new PanelPlayer());
        j.pack();
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.setVisible(true);
    }
}
